package synchronization

import (
	"fmt"
	"goDFS/etc"
	"goDFS/public"
	"goDFS/requests"
	"net/http"
	"time"
)

//发起同步到tracker
func SyncTracker(conf *etc.Conf, key string, localAddr string) {
	url := fmt.Sprintf("http://%s:%d/%s%s",
		conf.GetTracker().Host, conf.GetTracker().Port, public.ApiGroupName, public.SyncFileApi)

	parms := map[string]string{
		"local": localAddr,
		"key":   key,
	}

	url = requests.GetUrlBuild(url, parms)

	_, err := http.Get(url)
	if err != nil {
		etc.SaveLog("[ SyncTracker ]"+err.Error(), 2)
		return
	}

}

//对storage发送同步消息
func SendSyncMsg(addr *SyncFileAddress, addrList []*public.StorageAddr) {
	cash := make(chan int, len(addrList))     //用来同步管道
	ticker := time.NewTimer(time.Second * 20) //保证不出现永久同步失败

	for _, v := range addrList {
		//不需要对自己同步
		if addr.GetAddr() != v.GetAddr() {

			//发起同步请求
			go func() {
				url := fmt.Sprintf("http://%s:%d%s",
					v.Ip, v.Port, public.SyncFileApi)

				parms := map[string]string{
					"ip":   addr.Ip,
					"port": fmt.Sprintf("%d", addr.Port),
					"key":  addr.Key,
				}

				//构建请求url
				url = requests.GetUrlBuild(url, parms)
				_, err := http.Get(url)
				if err != nil {
					etc.SaveLog(fmt.Sprintf("%s", err), etc.Error)
					//fmt.Println(err)
					return
				}

				cash <- 1

			}()
		}
	}

	//保证全部同步完成

	for i := 0; i < len(addrList)-1; i++ {
		select {
		case <-cash:
		case <-ticker.C:
			etc.SaveLog(fmt.Sprintf("%s同步失败", addr.Key), etc.Error)
			fmt.Println(addr.Key, "同步失败")
			return
		}
	}

	etc.SaveLog(fmt.Sprintf("%s同步成功", addr.Key), etc.Info)
	//fmt.Println(addr.Key, "同步成功")

}
